package com.heima.schedule.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;


@Service
@Transactional
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskinfoLogsMapper logsMapper;

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);
        //2.添加任务到redis
        if (success) {
            addTaskToCache(task);
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId 任务id
     * @return 取消结果
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag = false;

        //删除任务，更新日志
        Task task = updateDb(taskId, ScheduleConstants.CANCELLED);

        //删除redis的数据
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }


        return flag;
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        String key = type + "_" + priority;
        String json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (StringUtils.isNotEmpty(json)) {
            Task task = JSON.parseObject(json, Task.class);

            //更新数据库信息
            updateDb(task.getTaskId() , ScheduleConstants.EXECUTED);

            return task;
        }

        return null;
    }


    /**
     * 每分钟定时刷新zset中的数据到list中
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void refresh() {
        //获取分布式锁如果成功则执行任务
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (null != token){
            //获取所有未来数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

            //遍历集合
            for (String futureKey : futureKeys) {
                //获取当前过期的任务
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                //通过ScheduleConstants.FUTURE分割
                String topicKeys = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                if (!tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey ,topicKeys,tasks);
                }

            }
        }
    }

    @PostConstruct//对象初始化方法,当对象创建完成就会调用该方法完成数据的初始化操作
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //清理Redis中的数据-list zset
        clearRedis();

        //查询未来5分钟之内要执行的任务
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        Date time = calendar.getTime();
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, time));
        //重新把任务添加到redis的缓存
        if (taskinfos != null && taskinfos.size() > 0) {
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo , task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());

                //添加到redis
                addTaskToCache(task);
            }
        }
    }

    /**
     * 清理Redis中的数据-list zset
     */
    private void clearRedis() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");

        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }

    /**
     * //删除redis的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //删除list里的数据
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新日志
     *
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        //根据id 删除任务数据
        taskinfoMapper.deleteById(taskId);
        //更新日志表的状态数据
        TaskinfoLogs logs = logsMapper.selectById(taskId);
        logs.setStatus(status);
        logsMapper.updateById(logs);
        Task task = new Task();
        BeanUtils.copyProperties(logs, task);
        task.setExecuteTime(logs.getExecuteTime().getTime());
        return task;
    }

    /**
     * 2.添加任务到redis
     *
     * @param task
     */
    private void addTaskToCache(Task task) {
        //设置key
        String key = task.getTaskType() + "_" + task.getPriority();

        //用日历类来完成时间操作
        Calendar calendar = Calendar.getInstance();//用当前时间初始化一个日历
        calendar.add(Calendar.MINUTE, 5);//把日历时间设置到了未来5分钟
        long future = calendar.getTimeInMillis();
        //1 如果任务的执行时间小于等于当前时间，存入list
        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= future) {
            //如果任务的执行时间小于等于当前时间+5分钟
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }

    }

    /**
     * 1.添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {

        //添加taskInfo表数据
        Taskinfo taskinfo = new Taskinfo();
        BeanUtils.copyProperties(task, taskinfo);
        taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
        int status = taskinfoMapper.insert(taskinfo);


        //添加 tsakInfoLogs 表数据
        TaskinfoLogs logs = new TaskinfoLogs();
        BeanUtils.copyProperties(taskinfo, logs);
        logs.setExecuteTime(new Date(task.getExecuteTime()));
        logs.setStatus(ScheduleConstants.SCHEDULED);
        logs.setVersion(1);
        logs.setTaskId(taskinfo.getTaskId());

        task.setTaskId(taskinfo.getTaskId());

        int result = logsMapper.insert(logs);

        return status == 1 && result == 1;
    }



}
